package com.example.mvvmtemplate.model;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.example.mvvmtemplate.base.viewmodel.BaseAndroidViewModel;
import com.example.mvvmtemplate.bean.LoginInfoBean;
import com.example.mvvmtemplate.repository.LoginRepository;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class LoginViewModel extends BaseAndroidViewModel {

    public LoginViewModel(@NonNull @NotNull Application application) {
        super(application);
    }

    private final MutableLiveData<LoginInfoBean> loginLiveData = new MutableLiveData<>();

    public MutableLiveData<LoginInfoBean> getLoginLiveData() {
        return loginLiveData;
    }

    /**
     * 登录
     */
    public void login(String name, String password, int userType) {
        Observable.create(new ObservableOnSubscribe<LoginInfoBean>() {
            @Override
            public void subscribe(@NotNull ObservableEmitter<LoginInfoBean> emitter) {
                try {
                    LoginInfoBean loginInfoBean = LoginRepository.login(getApplication(), name, password, userType);
                    emitter.onNext(loginInfoBean);
                } catch (IOException e) {
                    e.printStackTrace();
                    emitter.onError(e);
                }
            }
        }).subscribeOn(Schedulers.io())// 将被观察者切换到子线程
                .observeOn(AndroidSchedulers.mainThread())// 将观察者切换到主线程
                .subscribe(new Observer<LoginInfoBean>() {
                    private Disposable mDisposable;

                    @Override
                    public void onSubscribe(@NotNull Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(@NotNull LoginInfoBean value) {
                        loginLiveData.setValue(value);
                        mDisposable.dispose();//取消订阅
                    }

                    @Override
                    public void onError(@NotNull Throwable e) {
                        getThrowableLiveData().setValue(e);
                        mDisposable.dispose();//取消订阅
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

}
